package com.zeny.express.framework.core.database.masterslave;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class MasterSlaveContext {
	
	
	private static Map<String, MasterSlaveCluster> clusters = new HashMap<String, MasterSlaveCluster>();
	
	private static final Random random = new Random();
	
	public static void addCluster(MasterSlaveCluster cluster) {
		clusters.put(cluster.getClusterName(), cluster);
	}
	
	public static void setMaster(String clusterName) {
		MasterSlaveCluster cluster = clusters.get(clusterName);
		cluster.getCurrent().remove();
	}

	public static void setSlave(String clusterName) {
		MasterSlaveCluster cluster = clusters.get(clusterName);
		
		// 目前随机均分，TODO 后续可以配置权重
		int num = random.nextInt(cluster.getSlaves().size());
		
		String slave = cluster.getSlaves().get(num);
		cluster.getCurrent().set(slave);
	}
	
	public static String getDataSource(String clusterName) {
		MasterSlaveCluster cluster = clusters.get(clusterName);
		return (String)cluster.getCurrent().get();
	}

	public static void clearDataSource(String clusterName) {
		MasterSlaveCluster cluster = clusters.get(clusterName);
		cluster.getCurrent().remove();
	}
	
	public static void clearDataSource() {
		for (MasterSlaveCluster cluster : clusters.values()) {
			cluster.getCurrent().remove();
		}
	}
	
}
